<?php
class programme_cpl extends Model{
	public static function getTableName(){
		return 'programme_cpl';
	}

	/*
	 * by donald
	 */
    public function getPrimaryKey()
    {
        return array('programme_id', 'effective_date');
    }

	public function set($object)
	{
		$this->effective_date = !isset($object->effective_date) ? '' : $object->effective_date;
		$this->cpl_id = !isset($object->cpl_id) ? '' : trim($object->cpl_id);
		$this->cpl_company_code = !isset($object->cpl_company_code) ? '' : $object->cpl_company_code;
	}

	public function getCplByProgrammeID($id)
	{
		return Model::$dbo["r"]->findBySql(__class__, "select * from `programme_cpl` where programme_id='{$id}'");
	}

	public function delBySql($id)
	{
		return Model::$dbo["w"]->getDbHandle()->exec("delete from `programme_cpl` where programme_id='{$id}'");
	}

	public static function checkCpl($programme_no, $company_code)
	{
		#$sql = "select * from programme_cpl where cpl_id='{$programme_no}' and cpl_company_code='{$company_code}'";
		#$ret = Model::$dbo['r']->findBySql(__class__, $sql);
		#return isset($ret[0]) ? $ret[0]->programme_id : false;

		$sql = 'SELECT programme_id FROM programme_cpl WHERE cpl_id=:cpl_id AND cpl_company_code=:company_code';
		$ret = Model::selectBySql($sql, array(':cpl_id'=>$programme_no, ':company_code'=>$company_code));
		return isset($ret[0]['programme_id']) ? $ret[0]['programme_id'] : false;
	}

	public static function checkCplInMis($id)
	{
		#$sql = "select * from ".self::getTableName()." where path='{$path}'";
		#$ret = Model::$dbo['r']->findBySql(__class__, $sql);
		#return isset($ret[0]) ? $ret[0]->id : false;
        $result = self::getCplByProgrammeID($id);
        $match_data = array();
        if(!empty($result))
        {
            foreach($result as $record)
            {
                $cpl_id = $record->cpl_id;
                $co_code = $record->cpl_company_code;
                $sql = 'SELECT * FROM `pdes`.`mis_pdes` where co_code = :co_code and type= "programme" and mis_id = :pid';
                $ret = Model::selectBySql($sql, array(':co_code'=>$co_code,':pid'=>$cpl_id));
                if(!empty($ret))
                {
                    $match_data[] = array('programme_id'=>$id,'cpl_id'=>$cpl_id,'cpl_company_code'=>$co_code,'effective_date'=>$record->effective_date);
                }
            }
        }
        return $match_data;
	}

    public static function findPdesProgramme($cpl_id, $cpl_company_code='TVB')
    {
        $sql = 'SELECT `programme_id` FROM programme_cpl
            WHERE `cpl_id`=:cpl_id AND `cpl_company_code`=:cpl_company_code';
        $param = array(
            ':cpl_id'           => $cpl_id,
            ':cpl_company_code' => $cpl_company_code,
        );
        $ret = Model::selectBySql($sql, $param);

        return $ret;
    }
}
?>
